<template>
  <div class="product-detail-container">
    <!-- 返回按钮 -->
    <el-button
        type="primary"
        icon="el-icon-arrow-left"
        @click="goBack"
        class="back-btn"
    >
      返回商品列表
    </el-button>

    <!-- 商品详情内容 -->
    <div class="product-detail-content" v-if="productDetail">
      <!-- 商品图片展示 -->
      <div class="product-gallery">
        <el-carousel
            :interval="5000"
            arrow="always"
            height="500px"
            indicator-position="outside"
        >
          <el-carousel-item v-for="(img, index) in productImages" :key="index">
            <img :src="img" class="detail-image" alt="商品图片">
          </el-carousel-item>
        </el-carousel>
      </div>

      <!-- 商品基本信息 -->
      <div class="product-info">
        <h1 class="product-title">{{ productDetail.name }}</h1>

        <div class="price-section">
          <span class="current-price">¥{{ productDetail.price.toFixed(2) }}</span>
          <span class="original-price" v-if="productDetail.originalPrice">¥{{ productDetail.originalPrice.toFixed(2) }}</span>
          <span class="sales">已售 {{ productDetail.sales || 0 }}件</span>
        </div>

        <div class="meta-info">
          <div class="meta-item">
            <span class="label">库存：</span>
            <span class="value" :class="{'low-stock': productDetail.stock <= 10}">{{ productDetail.stock }}件</span>
          </div>
          <div class="meta-item" v-if="productDetail.origin">
            <span class="label">产地：</span>
            <span class="value">{{ productDetail.origin }}</span>
          </div>
          <div class="meta-item" v-if="productDetail.unit">
            <span class="label">单位：</span>
            <span class="value">{{ productDetail.unit }}</span>
          </div>
          <div class="meta-item" v-if="productDetail.categoryName">
            <span class="label">分类：</span>
            <el-tag size="small" effect="plain">{{ productDetail.categoryName }}</el-tag>
          </div>
        </div>

        <!-- 商品描述 -->
        <div class="product-description">
          <h3 class="section-title">商品描述</h3>
          <p class="description-content">{{ productDetail.description || '暂无详细描述' }}</p>
        </div>

        <!-- 商品参数 -->
        <div class="product-specs" v-if="productDetail.specs">
          <h3 class="section-title">规格参数</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item
                v-for="(value, key) in productDetail.specs"
                :key="key"
                :label="key"
            >
              {{ value }}
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
          <el-button
              type="danger"
              size="large"
              @click="addToCart"
              :disabled="productDetail.stock <= 0"
              :icon="productDetail.stock <= 0 ? 'el-icon-close' : 'el-icon-shopping-cart'"
              round
          >
            {{ productDetail.stock <= 0 ? '已售罄' : '加入购物车' }}
          </el-button>
          <el-button
              type="warning"
              size="large"
              @click="buyNow"
              :disabled="productDetail.stock <= 0"
              :icon="productDetail.stock <= 0 ? 'el-icon-close' : 'el-icon-s-promotion'"
              round
          >
            {{ productDetail.stock <= 0 ? '无库存' : '立即购买' }}
          </el-button>
        </div>
      </div>
    </div>

    <!-- 商品评论 -->
    <div class="product-reviews" v-if="review.length > 0">
      <h2 class="section-title">商品评价</h2>
      <el-card shadow="hover" class="review-card">
        <el-table :data="review" style="width: 100%">
          <el-table-column prop="userId" label="用户" align="center" width="120">
            <template #default="{row}">
              <el-avatar :size="30" :src="row.userAvatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" />
              {{ row.userId }}
            </template>
          </el-table-column>
          <el-table-column prop="rating" label="评分" align="center" width="100">
            <template #default="{row}">
              <el-rate
                  v-model="row.rating"
                  disabled
                  disabled-void-color="#ff9900"
                  void-color="#e8e8e8"
                  :colors="['#ff9900', '#ff9900', '#ff9900']"
              />
            </template>
          </el-table-column>
          <el-table-column prop="content" label="用户评论" align="center" min-width="200">
            <template #default="{row}">
              <div class="review-content">
                <p>{{ row.content }}</p>
                <div class="review-images" v-if="row.images && row.images.length > 0">
                  <el-image
                      v-for="(img, idx) in row.images.slice(0,3)"
                      :key="idx"
                      :src="img"
                      :preview-src-list="row.images"
                      fit="cover"
                      style="width: 50px; height: 50px; margin-right: 5px;"
                  />
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="评论时间" align="center" width="180" />
          <el-table-column prop="reply" label="商家回复" align="center" min-width="150">
            <template #default="{row}">
              <div class="seller-reply" v-if="row.reply">
                <div class="reply-content">{{ row.reply }}</div>
                <div class="reply-time">{{ row.replyTime }}</div>
              </div>
              <div v-else class="no-reply">暂无回复</div>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 购物车弹窗 -->
    <el-dialog
        v-model="cartDialogVisible"
        title="加入购物车"
        width="30%"
        @close="handleCartDialogClose"
    >
      <div class="dialog-product-info">
        <el-image
            :src="productImages[0]"
            fit="contain"
            style="width: 100px; height: 100px; margin-right: 15px;"
        />
        <div class="dialog-product-details">
          <h3>{{ productDetail.name }}</h3>
          <p class="price">¥{{ productDetail.price.toFixed(2) }}</p>
          <p class="stock">库存: {{ productDetail.stock }}件</p>
        </div>
      </div>

      <el-form :model="cartForm" label-width="80px" class="cart-form">
        <el-form-item label="购买数量">
          <el-input-number
              v-model="cartForm.quantity"
              :min="1"
              :max="productDetail.stock"
              controls-position="right"
              size="large"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="cartDialogVisible = false" size="large">取消</el-button>
        <el-button type="primary" @click="confirmAddToCart" size="large">确定</el-button>
      </template>
    </el-dialog>

    <!-- 购买弹窗 -->
    <el-dialog
        v-model="buyDialogVisible"
        title="确认订单"
        width="50%"
        @close="handleBuyDialogClose"
    >
      <div class="dialog-product-info">
        <el-image
            :src="productImages[0]"
            fit="contain"
            style="width: 120px; height: 120px; margin-right: 20px;"
        />
        <div class="dialog-product-details">
          <h3>{{ productDetail.name }}</h3>
          <p class="price">¥{{ productDetail.price.toFixed(2) }}</p>
          <p class="stock">库存: {{ productDetail.stock }}件</p>
        </div>
      </div>

      <el-form :model="orderForm" label-width="100px" class="order-form">
        <el-form-item label="收货地址" required>
          <el-input v-model="orderForm.shippingAddress" placeholder="请输入收货地址" size="large" />
        </el-form-item>
        <el-form-item label="联系电话" required>
          <el-input v-model="orderForm.contactPhone" placeholder="请输入联系电话" size="large" />
        </el-form-item>
        <el-form-item label="联系人" required>
          <el-input v-model="orderForm.contactName" placeholder="请输入收货人姓名" size="large" />
        </el-form-item>
        <el-form-item label="支付方式" required>
          <el-select v-model="orderForm.paymentType" placeholder="请选择支付方式" size="large" style="width: 100%">
            <el-option label="微信支付" :value="1" />
            <el-option label="支付宝" :value="2" />
            <el-option label="银行卡" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="运费">
          <p class="freight-info">¥{{orderForm.freight.toFixed(2)}}</p>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
              v-model="orderForm.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入备注信息"
              size="large"
          />
        </el-form-item>

        <el-form-item label="购买数量">
          <el-input-number
              v-model="orderForm.items[0].quantity"
              :min="1"
              :max="productDetail.stock"
              controls-position="right"
              size="large"
          />
        </el-form-item>
      </el-form>

      <div class="order-summary">
        <div class="summary-item">
          <span>商品总价:</span>
          <span class="value">¥{{ (orderForm.items[0].price * orderForm.items[0].quantity).toFixed(2) }}</span>
        </div>
        <div class="summary-item">
          <span>运费:</span>
          <span class="value">¥{{ orderForm.freight.toFixed(2) }}</span>
        </div>
        <div class="summary-item total">
          <span>应付总额:</span>
          <span class="value">¥{{ (orderForm.items[0].price * orderForm.items[0].quantity + orderForm.freight).toFixed(2) }}</span>
        </div>
      </div>

      <template #footer>
        <el-button @click="buyDialogVisible = false" size="large">取消</el-button>
        <el-button type="primary" @click="confirmBuy" size="large">提交订单</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()

// 商品详情数据
const productDetail = ref(null)
const loading = ref(true)
const error = ref(false)
const review = ref([])

// 弹窗控制
const cartDialogVisible = ref(false)
const buyDialogVisible = ref(false)

// 购物车表单
const cartForm = ref({
  quantity: 1
})

// 订单表单
const orderForm = ref({
  userId: null,
  merchantId: 0,
  shippingAddress: '',
  contactPhone: '',
  contactName: '',
  remark: '',
  items: [
    {
      productId: null,
      productName: '',
      productImage: '',
      quantity: 1,
      price: 0
    }
  ],
  freight: 10,
  paymentType: 1
})

// 获取商品ID
const productId = route.query.id

// 商品图片数组
const productImages = ref([])

// 加载商品详情
const loadProductDetail = async () => {
  try {
    loading.value = true
    error.value = false

    const response = await axios.get(BASE_URL+'/api/v1/product/detail', {
      params: { id: productId }
    })

    if (response.data.code == 2000) {
      productDetail.value = response.data.data
      // 处理图片数据
      if (productDetail.value.imageUrls && productDetail.value.imageUrls.length > 0) {
        productImages.value = productDetail.value.imageUrls.split(',').map(url => url.trim())
      } else {
        productImages.value = ['https://via.placeholder.com/800x600?text=No+Image']
      }

      // 初始化订单商品信息
      orderForm.value.items[0] = {
        productId: productDetail.value.id,
        productName: productDetail.value.name,
        productImage: productImages.value[0],
        quantity: 1,
        price: productDetail.value.price
      }
    } else {
      throw new Error(response.data.msg || '获取商品详情失败')
    }
  } catch (err) {
    error.value = true
    ElMessage.error(err.message)
  } finally {
    loading.value = false
  }
}

// 加载评论详情
const loadReview = async () => {
  try {
    const response = await axios.get(BASE_URL+'/api/v1/review/public/review_select', {
      params: { productId: productId }
    })

    if (response.data.code == 2000) {
      review.value = response.data.data.map(item => ({
        ...item,
        // 确保有images数组，即使为空
        images: item.images ? item.images.split(',') : []
      }))
    } else {
      ElMessage.error(response.data.msg)
    }
  } catch (error) {
    ElMessage.error('加载评论失败: ' + error.message)
  }
}

// 加入购物车
const addToCart = () => {
  cartForm.value.quantity = 1
  cartDialogVisible.value = true
}

// 确认加入购物车
const confirmAddToCart = async () => {
  try {
    const response = await axios.post(BASE_URL+'/api/v1/cart/add', {
      productId: productDetail.value.id,
      quantity: cartForm.value.quantity,
      productName: productDetail.value.name
    })

    if (response.data.code == 2000) {
      ElMessage.success('已成功加入购物车')
      loadProducts()
      cartDialogVisible.value = false
    } else {
      ElMessage.error(response.data.msg || '加入购物车失败')
    }
  } catch (error) {
    ElMessage.error('加入购物车失败: ' + error.message)
  }
}

// 购物车商品数量
const cartCount = ref(0)
const cartArr = ref([])

// 加载购物车商品
const loadProducts = () => {
  axios.get(BASE_URL+'/api/v1/cart/select').then((response) => {
    if (response.data.code == 2000) {
      cartArr.value = response.data.data
      cartCount.value = cartArr.value.length
    } else {
      ElMessage.error(response.data.msg)
    }
  })
}

// 立即购买
const buyNow = () => {
  // 更新商品信息
  orderForm.value.items[0] = {
    productId: productDetail.value.id,
    productName: productDetail.value.name,
    productImage: productImages.value[0],
    quantity: 1,
    price: productDetail.value.price
  }
  buyDialogVisible.value = true
}

// 确认购买
const confirmBuy = async () => {
  try {
    // 验证必填字段
    if (!orderForm.value.shippingAddress) {
      ElMessage.warning('请输入收货地址')
      return
    }
    if (!orderForm.value.contactPhone) {
      ElMessage.warning('请输入联系电话')
      return
    }
    if (!orderForm.value.contactName) {
      ElMessage.warning('请输入收货人姓名')
      return
    }

    // 设置用户ID和商家ID
    orderForm.value.userId = getUser().id;
    orderForm.value.merchantId = productDetail.value.merchantId

    const response = await axios.post(BASE_URL+'/api/v1/order/private/create', orderForm.value)

    if (response.data.code == 2000) {
      ElMessage.success('订单创建成功')
      buyDialogVisible.value = false
      // 跳转到订单支付页面
      // router.push(`/order/pay?id=${response.data.data.orderId}`)
    } else {
      ElMessage.error(response.data.msg || '订单创建失败')
    }
  } catch (error) {
    ElMessage.error('订单创建失败: ' + error.message)
  }
}

// 弹窗关闭处理
const handleCartDialogClose = () => {
  cartForm.value.quantity = 1
}

const handleBuyDialogClose = () => {
  orderForm.value.items[0].quantity = 1
}

// 返回商品列表
const goBack = () => {
  router.go(-1)
}

// 组件挂载时加载数据
onMounted(() => {
  if (!productId) {
    ElMessage.error('商品ID不存在')
    router.push('/products')
    return
  }
  loadProductDetail()
  loadProducts()
  loadReview()
})

// 模拟获取当前用户ID
const getCurrentUserId = () => {
  // 实际项目中应该从Vuex或Pinia中获取
  return 1 // 示例ID
}
</script>

<style scoped>
.product-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f7f7f7;
}

.back-btn {
  margin-bottom: 20px;
  font-size: 14px;
}

.product-detail-content {
  display: flex;
  gap: 30px;
  margin-bottom: 30px;
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.product-gallery {
  flex: 1;
  min-width: 0;
  border-radius: 4px;
  overflow: hidden;
}

.detail-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.product-info {
  flex: 1;
  min-width: 0;
}

.product-title {
  font-size: 24px;
  color: #333;
  margin-bottom: 15px;
  font-weight: 600;
  line-height: 1.3;
}

.price-section {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.current-price {
  font-size: 28px;
  color: #f56c6c;
  font-weight: bold;
  margin-right: 15px;
}

.original-price {
  font-size: 16px;
  color: #999;
  text-decoration: line-through;
  margin-right: 15px;
}

.sales {
  font-size: 14px;
  color: #999;
}

.meta-info {
  margin-bottom: 25px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.meta-item {
  margin-bottom: 12px;
  font-size: 14px;
  display: flex;
  align-items: center;
}

.meta-item:last-child {
  margin-bottom: 0;
}

.label {
  color: #666;
  display: inline-block;
  width: 60px;
  flex-shrink: 0;
}

.value {
  color: #333;
}

.low-stock {
  color: #f56c6c;
}

.product-description {
  margin-bottom: 25px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.product-specs {
  margin-bottom: 25px;
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.section-title {
  font-size: 18px;
  color: #333;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
  font-weight: 600;
}

.description-content {
  font-size: 14px;
  color: #666;
  line-height: 1.8;
  white-space: pre-line;
}

.action-buttons {
  display: flex;
  gap: 15px;
  margin-top: 30px;
}

.action-buttons .el-button {
  flex: 1;
  padding: 15px 0;
  font-size: 16px;
  height: auto;
}

.product-reviews {
  margin-top: 30px;
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.review-card {
  margin-top: 15px;
  border-radius: 8px;
}

.review-content {
  text-align: left;
  padding: 10px 0;
}

.review-images {
  margin-top: 8px;
  display: flex;
  flex-wrap: wrap;
}

.seller-reply {
  background-color: #f9f9f9;
  padding: 10px;
  border-radius: 4px;
  text-align: left;
}

.reply-content {
  color: #666;
  margin-bottom: 5px;
}

.reply-time {
  color: #999;
  font-size: 12px;
}

.no-reply {
  color: #999;
  font-size: 13px;
}

/* 对话框样式 */
.dialog-product-info {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.dialog-product-details {
  flex: 1;
}

.dialog-product-details h3 {
  margin: 0 0 8px 0;
  font-size: 16px;
  color: #333;
}

.dialog-product-details .price {
  color: #f56c6c;
  font-weight: bold;
  margin-bottom: 5px;
}

.dialog-product-details .stock {
  color: #999;
  font-size: 13px;
}

.cart-form, .order-form {
  margin-top: 20px;
}

.order-summary {
  margin-top: 20px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 4px;
  text-align: right;
}

.summary-item {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-bottom: 8px;
  font-size: 14px;
}

.summary-item:last-child {
  margin-bottom: 0;
}

.summary-item .value {
  margin-left: 10px;
  font-weight: 500;
}

.summary-item.total {
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px dashed #ddd;
  font-size: 16px;
}

.summary-item.total .value {
  color: #f56c6c;
  font-size: 18px;
}

.freight-info {
  margin: 0;
  color: #666;
}

@media (max-width: 768px) {
  .product-detail-content {
    flex-direction: column;
    padding: 15px;
  }

  .product-gallery {
    margin-bottom: 20px;
  }

  .action-buttons {
    flex-direction: column;
  }
}
</style>